
function getStringBetween(str, start, end) {
    str = (str + "").split(start)
    if (str.length < 2) return "";
    return (str[1] + "").split(end)[0];
}

function toLocaleUpperCase2(text1) {
    var content = text1.split("_")
    var conthentoks = [];
    for (var inde in content) {
        var name = (content[inde] + "");

        conthentoks.push(name.charAt(0).toUpperCase() + name.slice(1))
    }

    text1 = conthentoks.join("")
    return text1
}


function lookFile(path) {
    path=path.replace("\\","/");
    //通过这种方式弹出的层，每当它被选择，就会置顶。
    /*window.open(path);
    return;*/
    $.ajax({
        url:'/tool/lookfile?',
        type:'get',
        data:{path:path},
        success:function(result){
            layer.open({
                type: 1,
                title:path,
                shade: false,
                area: ["90%","90%"],
                maxmin: true,
                content: result,
                zIndex: layer.zIndex, //重点1
                success: function(layero){
                    layer.setTop(layero); //重点2
                }
            });
        }});

}

var $,form;

layui_use()
function form_render(time,fun) {
    time = time || 120;
    setTimeout(function (){
        form.render();
        if(fun){
            fun();
        }
    },time)
}
function layui_use(){
    setTimeout(function () {

            layui.use(['form'], function() {
                $ = layui.$
                    , form = layui.form
                submitID = 'layuiadmin-form-role';
                form.render();

                form.on('select(dbtable)', function (data) {
                    vuell.select_table = vuell.tables[data.value];
                    //vuell.list_table = vuell.select_table;
                    vuell.list_table_edit(vuell.select_table);
                    vuell.controller =firstToUpper1(data.value.replace(vuell.table_pf,"").replace(/_/g,""))+"Controller";
                    //vuell.list_table = [];
                    form_render();
                });

                form.on('select(retable)', function (data) {
                    console.log(data)
                    var keydata=data.value.split('-');
                    vuell.re_tables[keydata[1]] = vuell.tables[keydata[0]];
                    vuell.$set(vuell.re_tables,vuell.re_tables)
                    //console.log(vuell.tables[keydata[0]])
                    vuell.list_table_edit(vuell.tables[keydata[0]],'a'+keydata[1]+'.');
                    form_render(200,function (){
                        var data1 = form.val(submitID);
                        console.log(data1)
                    });
                });

            });
        }
        ,200);
}

var vuell= new Vue({
    el: "#vueapp",
    data:{
        routes:{
            "add":1,
            "dele":1,
            "edit":1,
            "list":1,
        },
        check_types:{
            'required':'必填项',
            'required|phone':'手机号',
            'required|email':'邮箱',
            'required|url':'网址',
            'required|number':'数字',
            'required|date':'日期',
            'required|identity':'身份证',
        },
        input_types:{
            'input':'单行输入框',
            'textarea':'多行输入框',
            'select':'下拉选择框',
            'radio':'单选框',
            'checkbox':'多选框',
            'uploadimage':'图片上传',
            'uploadfile':'文件上传',
            'layedit':'layui富文本编辑器',
        },list_types:{
            'text':'文字',
            'image':'图片',
            'type':'固定状态',
            'timedate':'时间搓转时间',
            'link_opend':'弹窗打开链接',

        },
        controller:'',
        controllername:'',
        table_pf:'',//表前缀
        tables:[],
        select_table:{},
        list_table:[],
        re_tables:[],//关联表
        re_tables_table:[],//已关联表
        re_tables_fi:[],//已关联字段
        filePath:[],
        mysqltable:""
    },
    mounted () {

        var kk= window.localStorage.getItem("filePath");
        if(kk!=undefined){
            this.filePath=JSON.parse(kk);
        }
         kk= window.localStorage.getItem("mysqltable");
        if(kk!=undefined){
            this.mysqltable=(kk);
        }
        this.get_tables()
    },
    methods: {
        submit(){
            var formdata = form.val(submitID);
            if(formdata.table==''){
                layer.msg("请选择数据库");return;
            }
            if(formdata.controller==''){
                layer.msg("控制器不能为空");return;
            }
            if(formdata.controllername=='' && formdata.table!='zdymydqltable'){
                layer.msg("名称不能为空");return;
            }
            var _this=this;
            var pushdata ={
                'table':formdata.table.replace(vuell.table_pf,""),
                'controller':formdata.controller,
                'controllername':formdata.controllername,
                'buttons_show_so':formdata.buttons_show_so??0,
                'add':{
                    'status':_this.routes.add,
                    'list':[]
                },
                'edit':{
                    'status':_this.routes.edit,
                    'list':[]
                },
                'dele':{
                    'status':_this.routes.dele,
                    'list':[]
                },'lists':{
                    'status':_this.routes.list,
                    'list':[]
                },'join':[]
                ,'buttons_top':[]
                ,'buttons_rigth':[]
                ,'buttons_row':[]
            };


            if(pushdata.add.status || pushdata.edit.status ){
                var i=0;
                for (var it in _this.select_table){
                    var add_fied = 'add_fied[' + i + ']';
                    var add_type = 'add_type[' + i + ']';
                    var add_title = 'add_title[' + i + ']';
                    var add_checktype = 'add_checktype[' + i + ']';
                    var add_status = 'add_status[' + i + ']';
                    if(formdata[add_fied]){
                        pushdata.add.list.push({
                            "fied":formdata[add_fied],
                            'type':formdata[add_type],
                            'title':formdata[add_title],
                            'checktype':formdata[add_checktype],
                            'add_status':formdata[add_status],
                        });
                    }
                    i++;
                }
                pushdata.edit.list = pushdata.add.list;
            }

            if(pushdata.lists.status){
                var i=0;
                for (var it in _this.list_table){
                    var list_fied = 'list_fied[' + i + ']';
                    var list_total = 'list_total[' + i + ']';
                    var list_title = 'list_title[' + i + ']';
                    var list_so = 'list_so[' + i + ']';
                    var list_order = 'list_order[' + i + ']';
                    var list_type = 'list_type[' + i + ']';
                    var list_type_status = 'list_type_status[' + i + ']';
                    if(formdata[list_fied]){
                        pushdata.lists.list.push({
                            "fied":formdata[list_fied]??0,
                            'total':formdata[list_total]??0,
                            'title':formdata[list_title]??0,
                            'so':formdata[list_so]??0,
                            'order':formdata[list_order]??0,
                            'list_type':formdata[list_type]??'',
                            'list_type_status':formdata[list_type_status]??'',
                        });
                    }
                    i++;
                }
                var i=0;
                for (var it in _this.re_tables){
                    var re_tables = 're_tables[' + i + ']';
                    var re_tables_fi_old = 're_tables_fi_old[' + i + ']';
                    var re_tables_fi = 're_tables_fi[' + i + ']';
                    var re_tables_type = 're_tables_type[' + i + ']';
                    if(formdata[re_tables] && formdata[re_tables_fi_old] && formdata[re_tables_fi]){
                        pushdata.join.push({
                            "fied":formdata[re_tables_fi]??0,
                            'table':formdata[re_tables].replace(vuell.table_pf,"").split('-')[0]+' as a'+i,
                            'fied_old':formdata[re_tables_fi_old],
                            'join':formdata[re_tables_type]??'Left',
                        });
                    }
                    i++;
                }

                for (var i=0;i< 10;i++){
                    var buttons_top = 'buttons_top[' + i + ']';
                    if(formdata[buttons_top]){
                        pushdata.buttons_top.push(formdata[buttons_top]);
                    }
                    var buttons_row = 'buttons_row[' + i + ']';
                    if(formdata[buttons_row]){
                        pushdata.buttons_row.push(formdata[buttons_row]);
                    }
                    var buttons_rigth = 'buttons_rigth[' + i + ']';
                    if(formdata[buttons_rigth]){
                        pushdata.buttons_rigth.push(formdata[buttons_rigth]);
                    }
                }
            }

            console.log(formdata)
            console.log(pushdata)



            $.ajax({
                url:'/tool/make?',
                type:'POST',
                data:pushdata,
                success:function(result){
                    _this.filePath=(result.data);
                    window.localStorage.setItem("filePath",JSON.stringify(_this.filePath));
                    layer.alert("文件已生成！在下方查看最新文件")
                }});
        },
        remove_re_tables(index){
            this.re_tables.splice(index,1);
        },
        add_re_tables(){
            this.re_tables.push([]);
            form_render();
        },
        list_table_edit(tabledata,fx){
            fx = fx || '';
            // this.list_table = [];
            for (var i in tabledata ){
                tabledata[i].order=0;
                tabledata[i].total=0;
                tabledata[i].so=0;
                tabledata[i].check=fx?0:1;
                tabledata[i].fied=fx+tabledata[i].fied;
                this.list_table.push(tabledata[i]);
            }
            console.log(tabledata)
        },
        deleMake(){
            var _this = this;
            if(_this.controller==''){
                layer.alert("请先选择库或者直接填写控制器名称！");
                return;
            }
            layer.confirm('本次删除会删除 '+_this.controller+' 之前生成的所有文件，确定吗？', function(index) {

                //执行 Ajax 后重载
                $.ajax({
                    url:'/tool/dele',
                    type:'POST',
                    data:{controller:_this.controller},
                    success:function(result){
                        layer.msg(result.message)
                        if(result.code==200){
                            _this.get_data();
                        }

                    }});

            });
        },
        get_tables(){
            var _this=this;
            if (_this.mysqltable != ""){
                /*if (this.mysqltable == "") {
                    layer.alert("mysql文本不能为空");
                    return;
                }*/
                _this.tables = this.Djencode(this.mysqltable).tables;
                //_this.select_table=
                _this.table_pf = "sl_";
                layui_use();
                return;
            }

            //提交 Ajax 成功后，静态更新表格中的数据
            $.ajax({
                url:'?',
                type:'GET',
                success:function(result){
                    if(result.code==200){
                        _this.tables = result.data.tables;
                        _this.table_pf = result.data.table_prefix;

                        layui_use()

                    }

                }});
        }, Djencode(mysqltable) {//生成go struct


            window.localStorage.setItem("mysqltable", mysqltable);

            var _this = this;
            var content = mysqltable.split("\n");
            var tablename = getStringBetween(content, "='", "';");
            var table12 = getStringBetween(content, "CREATE TABLE " + "`", "`");
            table12 = "zdymydqltable";
            var tabledx = toLocaleUpperCase2(table12);
            var conthentoksjson = {};
            var retruenobj = {"tables": {}, "table": table12}
            for (inde in content) {

                var content1 = content[inde];
                content1 = content1.trim()
                if (content1.slice(0, 1) == "`") {
                    //`vid` int(11) NOT NULL AUTO_INCREMENT,
                    //`visiter_id` varchar(200) NOT NULL COMMENT '访客id',
                    //Vid         int32  `gorm:"column:vid;type:INT(11);AUTO_INCREMENT;NOT NULL"`

                    var vid = getStringBetween(content1, "`", "`")
                    var remark = getStringBetween(content1, "'", "'")
                    content1 = getStringBetween(content1, vid + "` ", " COMMENT '")
                    var columns = content1.toUpperCase().replace(",", "").split(" ")
                    var vidd = toLocaleUpperCase2(vid) //首字母大写
                    var notnull = "";
                    var AUTO_INCREMENT = "";
                    if (content1.indexOf("NOT NULL") != -1) {
                        notnull = "NOT NULL";
                    }
                    if (content1.indexOf("AUTO_INCREMENT") != -1) {
                        AUTO_INCREMENT = "AUTO_INCREMENT";
                    }
                    var type = columns[0]
                    var gotype = "string"
                    if (type.indexOf("TINYINT") != -1) {
                        gotype = 'int8'
                    } else if (type.indexOf("INT") != -1) {
                        gotype = 'int32'
                    } else if (type.indexOf("DATE") != -1 || type.indexOf("TIMESTAMP") != -1) {
                        gotype = 'XTime'
                    } else if (type.indexOf("BOOL") != -1) {
                        gotype = 'bool'
                    } else if (type.indexOf("SMALLINT") != -1) {
                        gotype = 'int16'
                    } else if (type.indexOf("BIGINT") != -1) {
                        gotype = 'int64'
                    } else if (type.indexOf("FLOAT") != -1) {
                        gotype = 'float32'
                    }


                    /*    var strink2 = "	";
                        strink2+=vidd+"         "+gotype+' `gorm:"column:'+vid+';type:'+[type,notnull,AUTO_INCREMENT].join(";")+'"`   // '+(remark?remark:'')
                        strink2=strink2.replace(";;",";")
                        conthentoks.push(strink2)

                        strink2 = "	";
                        strink2+=vidd+"         "+gotype+' `json:"'+vidd+'"`   // '+(remark?remark:'')
                        strink2=strink2.replace(";;",";")

                        conthentoksjson.push(strink2)
                */
                    conthentoksjson[vidd] = {
                        "fied": vidd,
                        "gotype": gotype,
                        "type": gotype.indexOf("int") != -1 ? "int" : '',
                        "title": (remark ? remark : vidd),
                        "isnotnull": 1,
                        "tablename": table12
                    };

                    //console.log(conthentoksjson)
                }

            }

            retruenobj.tables[table12] = conthentoksjson
            return retruenobj;

            /*$.ajax({
                url:"./indexenjson",
                data:{str:_this.text1,strcode:_this.strcode},
                type:'post',
                success:function(result){
                    _this.text2 = result;
                }});*/
        }
    },
});


